#!/usr/bin/env python
import os
import cgi
import datetime
import logging

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import images
import database
from cookiemanager import LilCookies
import random
logging.getLogger().setLevel(logging.DEBUG)

def set_cookie(self):
    cookieutil = LilCookies(self, 'sadsadasdsadlakjdlasjdklsajdlkq32312312l3jlkejswqljsl1j2l321312sqws1232131swqs12321KLJKLJLJ231321eqwsasqe12')
    cookie_value = cookieutil.get_secure_cookie(name = 'cid')
    for i in range(5):
        random_number = str(random.random())
    if cookie_value is None:
        cookie_value = cookieutil.set_secure_cookie(name = 'cid', value = random_number, expires_days= 365*100)
    else:
        cookie_value= cookieutil.get_secure_cookie(name = 'cid')
    return cookie_value

class MainPage(webapp.RequestHandler):
	def get(self):
		set_cookie(self)
		result = 'result'
		template_values = {
			'result': result
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/index.html')
		self.response.out.write(template.render(path, template_values))

class Creatives(webapp.RequestHandler):
    def get(self):
        query_creatives = "SELECT * FROM Creatives"
        query_campaign = "SELECT * FROM Campaigns"
        creatives = database.db.GqlQuery(query_creatives)
        campaigns = database.db.GqlQuery(query_campaign)
        set_cookie(self)

        template_values = {
            'creatives': creatives,
            'campaigns': campaigns,
            }
        path = os.path.join(os.path.dirname(__file__), 'templates/creatives.html')
        self.response.out.write(template.render(path, template_values))

class GetTag(webapp.RequestHandler):
	def get(self):
		query_str = "SELECT * FROM Tags"
		tags = database.db.GqlQuery(query_str)
		template_values = {
		'tags': tags,
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/tags.html')
		self.response.out.write(template.render(path, template_values))

class PutTag(webapp.RequestHandler):
	def post(self):
		tag = database.Tags()
		if users.get_current_user():
			tag.user = users.get_current_user()
		tag.name = self.request.get("name")
		tag.width = int(self.request.get("width"))
		tag.height = int(self.request.get("height"))
		tag.tag = self.request.get("tag")
		tag.put()
		self.redirect('/')
		
class ImgTagGenerator (webapp.RequestHandler):
	def get(self):
		data = database.Creatives.get(self.request.get("i"))
		template_values = {
			'data': data,
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/taggenerator.html')
		self.response.out.write(template.render(path, template_values))

class UploadCreatives(webapp.RequestHandler):
    def post(self):
        creative = database.Creatives()
        if users.get_current_user():
            creative.user = users.get_current_user()
        creative.name = self.request.get("name")
        creative.width = int(self.request.get("width"))
        creative.height = int(self.request.get("height"))
        creative.url = self.request.get("url")
        creative_img = self.request.get("img")
        creative.campaign = database.db.get(self.request.get('campaign'))
        creative.data = db.Blob(creative_img)
        creative.put()
        self.redirect('/')



class Image (webapp.RequestHandler):
    def get(self):
        creative = database.db.get(self.request.get("img_id"))
        ipaddress = self.request.remote_addr
        useragent = self.request.headers['User-Agent']
        cookie_value = set_cookie(self)
        database.increment_impression(creative, ipaddress, useragent, cookie_value)
        if creative:
            self.response.headers['Content-Type'] = "image/png"
            self.response.out.write(creative.data)
        else:
            self.response.out.write("No image")

class JavascriptImage (webapp.RequestHandler):
	def get(self):
		set_cookie()
		data = database.Creatives.get(self.request.get("id"))
		template_values = {
			'data': data,
		}
		self.response.headers['Content-Type'] = "text/javascript"
		path = os.path.join(os.path.dirname(__file__), 'templates/javascript.html')
		self.response.out.write(template.render(path, template_values))
		

class ClickTracker (webapp.RequestHandler):
	def get(self):
		cookieutil = LilCookies(self, 'sadsadasdsadlakjdlasjdklsajdlkq32312312l3jlkejswqljsl1j2l321312sqws1232131swqs12321KLJKLJLJ231321eqwsasqe12')
		cookie_value = cookieutil.get_secure_cookie(name = 'cid')
		ipaddress = self.request.remote_addr
		useragent = self.request.headers['User-Agent']
		creative = database.db.get(self.request.get("i"))
		click = self.request.get("click")
		database.increment_click(creative, ipaddress, useragent, cookie_value, click)
		self.redirect(click)

class Advertisers(webapp.RequestHandler):
    def get(self):
        query_str = "SELECT * FROM Advertisers"
        advertisers = database.db.GqlQuery (query_str)
        set_cookie()

	template_values = {
            'advertisers': advertisers,
            }
	path = os.path.join(os.path.dirname(__file__), 'templates/advertisers.html')
        self.response.out.write(template.render(path, template_values))

class CreateAdvertiser(webapp.RequestHandler):
	def post(self):
		advertiser = database.Advertisers()
		if users.get_current_user():
			advertiser.user = users.get_current_user()
		advertiser.advertisername = self.request.get("advertisername")
		advertiser.url = self.request.get("url")
		advertiser.put()
		self.redirect('/clients/advertisers')

class Campaigns(webapp.RequestHandler):
	def get(self):
		query_str = "SELECT * FROM Campaigns"
		campaigns = database.db.GqlQuery (query_str)
		set_cookie(self)

		template_values = {
			'campaigns': campaigns,
			}
		path = os.path.join(os.path.dirname(__file__), 'templates/campaigns.html')
		self.response.out.write(template.render(path, template_values))

class CreateCampaign(webapp.RequestHandler):
	def post(self):
		campaign = database.Campaigns()
		if users.get_current_user():
			campaign.user = users.get_current_user()
		campaign.campaignname = self.request.get("campaignname")
		campaign.put()
		self.redirect('/clients/campaigns')
		
class CampaignStats(webapp.RequestHandler):
	def get(self):
		campaigns = database.db.GqlQuery("SELECT * FROM Campaigns")
		campaigns_template = []
		CAMPAIGNS = []
		for campaign in campaigns:
			creative_keys = []
			creatives = database.db.GqlQuery("SELECT * FROM Creatives WHERE campaign = :1", campaign.key())
			for creative in creatives:	
				creative_keys.append(creative.key())
			get_impressions = database.db.GqlQuery("SELECT * FROM ImpressionCounterShard WHERE creative in :1", creative_keys)
			t_impressions = 0
			for imp in get_impressions:
				t_impressions += imp.count
			get_clicks = database.db.GqlQuery("SELECT * FROM ClickCounterShard WHERE creative in :1", creative_keys)
			t_clicks = 0
			for clicks in get_clicks:
				t_clicks += clicks.count
			CAMPAIGNS.append({'name' : campaign.campaignname, 'impressions': t_impressions, 'clicks': t_clicks})
		campaigns = []
		for c in CAMPAIGNS:
			campaigns.append({
			'name': c['name'],
			'impressions': c['impressions'],
			'clicks': c['clicks']
			})
		template_values = {
			'campaigns': campaigns,
		}
		path = os.path.join(os.path.dirname(__file__), 'templates/campaignstats.html')
		self.response.out.write(template.render(path, template_values))
		
class CreativeStats(webapp.RequestHandler):
	def get(self):
		self.response.out.write('<html><body>')
		campaigns = database.db.GqlQuery("SELECT * FROM Campaigns WHERE __key__ = KEY(:1)", self.request.get('campaign'))
		creatives = database.db.GqlQuery("SELECT * FROM Creatives WHERE campaign = KEY(:1)", self.request.get('campaign'))
		for campaign in campaigns:
			if campaign.campaignname:
				self.response.out.write('<h2> Campaign: %s</h2>' % campaign.campaignname)
		creative_keys = []
		self.response.out.write('<table>')
		self.response.out.write('<tr><td>Creative Name</td><td>Impressions</td><td>Clicks</td></tr>')
		for creative in creatives:
				self.response.out.write('<tr>')
				if creative.name:
					self.response.out.write('<td>%s</td>' % creative.name)
				creative_impressions = database.db.GqlQuery("SELECT * FROM ImpressionCounterShard WHERE creative = :1", creative.key())
				creative_keys.append(creative.key())
				total_impressions = 0
				for impression in creative_impressions:
					total_impressions += impression.count
				self.response.out.write('<td>%s</td>' % total_impressions)
				creative_clicks = database.db.GqlQuery("SELECT * FROM ClickCounterShard WHERE creative = :1", creative.key())
				total_clicks = 0
				for click in creative_clicks:
					total_clicks += click.count
				self.response.out.write('<td>%s</td>' % total_clicks)
				self.response.out.write('</tr>')
		self.response.out.write('<tr><td>Total</td>')
		get_impressions = database.db.GqlQuery("SELECT * FROM ImpressionCounterShard WHERE creative IN :1", creative_keys)
		get_clicks = database.db.GqlQuery("SELECT * FROM ClickCounterShard WHERE creative IN :1", creative_keys)
		t_clicks = 0
		t_impressions = 0
		for imp in get_impressions:
			t_impressions += imp.count
		for clicks in get_clicks:
			t_clicks += clicks.count
		self.response.out.write('<td>%s</td>' % t_impressions)
		self.response.out.write('<td>%s</td>' % t_clicks)
		self.response.out.write('</tr></table>')
		self.response.out.write('</body></html>')

application = webapp.WSGIApplication([
    ('/', MainPage),
	('/clients/advertisers', Advertisers),
	('/clients/CreateAdvertiser', CreateAdvertiser),
	('/clients/campaigns', Campaigns),
	('/clients/creativestats', CreativeStats),
	('/clients/campaignstats', CampaignStats),
	('/clients/CreateCampaign', CreateCampaign),
    ('/Creatives', Creatives),
    ('/UploadCreatives', UploadCreatives),
    ('/SubmitTags', GetTag),
	('/PutTags', PutTag),
    ('/jump', ClickTracker),
	('/imgtag', ImgTagGenerator),
	('/adj', JavascriptImage),
    ('/img', Image)], debug=True)


def main():
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
